var cart =$api.getStorage('cart');   
var member=$api.getStorage('member');


var cartId =member.cartId;   //购物车ID

apiready = function () {
       
       
       //监听购物车变化  
        api.addEventListener({
		    name: 'getCartDate'
		}, function(ret){
		   getCartDate();    
		   
		});


       getCartDate();  //获取购物车数据
}

//获取购物车数据
function getCartDate(){
     
 	 api.showProgress({
	        title: '加载中...',
	        modal: false
	 });
	 
	 
//   if(cart){   //本地有保存
//	    	cart = $api.getStorage('cart');
//	    	showCartData();
//  }else{
	     $api.get(serviceUrl+'/app/member/cart?cartId='+cartId,function(ret){
		  	  cart = ret.carts;
              showCartData();  //显示购物车数据
		  	  
		},'json');
	//}

};

//显示购物车数据
function showCartData(){
     
     
	     if(cart.buyNum>0){
	         
	         $api.byId('nocart').style.display="none";
	         $api.byId('yescart').style.display="block";
	         $api.byId('jiesuan').style.display="block";
	        
	         $api.text($api.byId('cartTotal'), cart.total.toFixed(2));
	         $api.text($api.byId('cartbuyNum'), cart.buyNum);
	         
	         var proItem=cart.item;
	         
	
	         var aHtml='';
	         for(var i=0;i<proItem.length;i++){
	         
					aHtml+='<div id=\''+proItem[i]._id+'\' style="border-bottom:1px solid #eaedf1;padding:5px;">';
				     	aHtml+='<table  border="0" width="100%" style="margin-top:8px;table-layout:fixed;">';
				     	 	aHtml+='<tr>';
				     	 		aHtml+='<td rowspan="3" valign="middle" style="width:70px;">';
				     	 		    aHtml+='<img src="'+serviceUrl+'/files/'+(proItem[i].proDefImg||0)+'"  style="width:65px;height:70px;"/>';
				     	 		aHtml+='</td>';
				     	 		aHtml+='<td rowspan="2" width="60%"  style="word-break:break-all;font-size:14px"  valign="top">';
				     	 			aHtml+=proItem[i].proName;
				     	 		aHtml+='</td>';
				     	 		aHtml+='<td valign="top" align="right" >';
				     	 			            aHtml+='<img src="images/cart_delete.png"  onclick="removeItem(\''+proItem[i].id+'\')"  style="width: 20px;height: 20px">';
				     	 		aHtml+='</td>';
				     	 	aHtml+='</tr>';
				     	    aHtml+='<tr></tr>';
				     	 	aHtml+='<tr>';
				     	 		 aHtml+='<td  valign="bottom" align="left" style="font-size:10px;max-width:110px;">';
						  	 	  	 aHtml+='<div class="am-input-group am-input-group-sm">';
										aHtml+='<span class="am-input-group-btn">';
											aHtml+='<button class="am-btn am-btn-default" type="button" onclick="reduceItem(\''+proItem[i].id+'\')">';
												aHtml+='-';
											aHtml+='</button>';
										aHtml+='</span>';
										aHtml+='<input type="number" id="good_num_'+ proItem[i].id +'" readonly class="am-form-field am-text-center" style="height:28px;width:50px;" value="'+proItem[i].num+'"  readonly="">';
										aHtml+='<span class="am-input-group-btn" style="float:left">';
											aHtml+='<button class="am-btn am-btn-default" type="button" onclick="addItem(\''+proItem[i].id+'\')">';
												aHtml+='+';
											aHtml+='</button>';
										aHtml+='</span>';
									aHtml+='</div>';
					  	 	     aHtml+='</td>';
					  	 	     aHtml+='<td  valign="bottom"  style="color: red;text-align: right;font-size:13px" >';
					  	 	     aHtml+='￥'+proItem[i].price.toFixed(2);
					  	 	    aHtml+='</td>';
				     	 	aHtml+='</tr>';
					  	 aHtml+='</table>';
					 aHtml+='</div>';
		  	 
		       
	         
	         }
	        
	          	$api.html($api.byId('cartItem'), aHtml);
         
     
     
     }else{
           //购物车没商品    
            $api.byId('nocart').style.display="block";
            $api.byId('yescart').style.display="none";
            $api.byId('jiesuan').style.display="none";
         
     
     }
    
    api.hideProgress();

};



//加法
function addItem(id){
	var index = findIndex(cart.item,id);
	if(index != -1) {
		++cart.item[index].num;
		//$api.val($api.byId('good_num_'+id),cart.item[index].num);
	}
	calculation();

};



//减法
function reduceItem(id){
    	var index = findIndex(cart.item,id);
	if(index != -1) {
		if(cart.item[index].num > 1){
			--cart.item[index].num;
			calculation();
		} else {
			removeItem(id);
		}
	}

};

//计算
function calculation(){

        var totalprice = 0;
		var totalNum = 0
		
		for(var i=0;i<cart.item.length;i++){
			cart.item[i].total = cart.item[i].num * cart.item[i].price;
			totalprice += cart.item[i].total;
			totalNum += parseInt(cart.item[i].num,10);
		}
		// console.log();
		cart.cartId = cartId;
		cart.total = totalprice.toFixed(2);
		cart.buyNum = totalNum;
		
        
     //   alert(JSON.stringify(cart));
        
    //    return;
        
        //更新购物车
		do_ajax('/app/cart/update2','post',cart,function(respose,err) {
			api.hideProgress();
			if( respose.resultCode=="0"){
				$api.text($api.byId('total'), cart.total);
    		   	    $api.text($api.byId('buyNum'), cart.buyNum);
				
		
				
			    setTimeout(function () {
	                cart =respose.carts;
	                
	                		 //发送刷新购物车监听事件
			     	api.sendEvent({
					    name: 'refreshCart',     
					   // extra: address
					});
	                
	                showCartData();
	            }, 300);
			    
			}
		});

};

//删除
function  removeItem(id){
      api.confirm({title: '提示',msg:'是否从购物车中删除该商品?',buttons:['确定', '取消']},function(ret,err){
			if(ret.buttonIndex == 1){
				var index = findIndex(cart.item,id)
				// 如果找到了那个item
				if(index != -1) {
					//$scope.cartItem.splice(index, 1);
					cart.item.splice(index, 1);
					calculation();
				}
				$api.remove($api.byId(id));
			}
		});
};




//结算
function buy(){

     api.openWin({
        name: 'buycart',
        url: 'buycart.html',
        pageParam: {cart:cart},
        bounces: false,
        vScrollBarEnabled:false,
        hScrollBarEnabled:false,
        reload: true,
       }
    );
};



//清空购物车
function clearCart(){
  api.confirm({title: '提示',msg:'确定清空购物车?',buttons:['确定', '取消']},function(ret,err){
			if(ret.buttonIndex == 1){
				 	api.showProgress({
					        title: '加载中...',
					        modal: false
					});
					
					api.ajax({
						    url: serviceUrl+'/app/cart/clear',
						    method: 'post',
						   	timeout: 30,
						    dataType: 'json',
						    returnAll:false,
						    cache: false,
				        	timeout: 20,
						    headers: {
					            "Content-type": "application/json;charset=UTF-8"
					        },
						    data:{body:{cartId:member.cartId}}
						},function(result,err){
						    if(result.resultCode == '0') {
						    
						    $api.rmStorage('cart');  //清除本地的
						 //   $api.setStorage('cart',{'buyNum':0});
						    
						    //发送获取购物车监听事件
						    api.sendEvent({
							    name: 'refreshCart',     
							   // extra: address
							});
						    
					     	api.sendEvent({
							    name: 'getCartDate',     
							   // extra: address
							});
							 api.toast({
							    msg: '清空购物车成功',
							    duration:3000,
							    location: 'middle'
							});
								
							 }else{
							 	 api.toast({
								    msg: '清空购物车失败',
								    duration:3000,
								    location: 'middle'
								});
							 }
					        api.hideProgress();
						    
					});
				
			}
	});

};








